package com.sunwayworld.basemodule.rm.train.question.validator;

import com.sunwayworld.cloud.module.train.exam.bean.CoreExamQuestionBean;
import com.sunwayworld.cloud.module.train.exam.service.CoreExamQuestionService;
import com.sunwayworld.cloud.module.train.question.bean.CoreQuestionBean;
import com.sunwayworld.cloud.module.train.question.service.CoreQuestionService;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.utils.ArrayUtils;
import com.sunwayworld.framework.validator.data.DataValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class LimsCoreQuestionLastSuspendedValidator implements DataValidator {

    @Autowired
    @Lazy
    private CoreQuestionService coreQuestionService;

    @Autowired
    @Lazy
    private CoreExamQuestionService coreQuestionExamService;

    @Override
    public boolean doValid(Object... args) {
        RestJsonWrapperBean wrapper = (RestJsonWrapperBean) args[0];
        List<Long> ids = wrapper.parseId(Long.class);
        List<CoreExamQuestionBean> coreExamQuestionBeans = coreQuestionExamService.getDao().selectListByOneColumnValues(ids, "questionId", ArrayUtils.asList("id", "questionId"));
        if (!coreExamQuestionBeans.isEmpty()){
            List<Long> questionIds = coreExamQuestionBeans.stream().map(CoreExamQuestionBean::getQuestionId).distinct().collect(Collectors.toList());
            List<CoreQuestionBean> coreQuestionBeans = coreQuestionService.getDao().selectListByIds(questionIds);
            String msg = coreQuestionBeans.stream().map(CoreQuestionBean::getQuestionContent).collect(Collectors.joining("<br/>"));
            addConstraintViolation("以下题目"+"<br/>"+msg+"<br/>已被引用不能删除！");
            return false;
        }
        return true;
    }
}
